package com.diqizu.utli;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBManager {

	/**
	 * 获取连接的方法
	 * 
	 * @return
	 */
	public static Connection getConn() {
		try {
			// 1.加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			// 2.获取连接: 三个参数：数据库连接地址（数据库名） ， 数据库用户名 ， 密码
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/qizudb", "root", "admin");
			return conn;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 增删改方法
	 * 
	 * @param sql
	 * @return
	 */
	public static boolean execUpdate(String sql) {
		Connection conn = null;
		Statement sta = null;
		try {
			conn = getConn();
			sta = conn.createStatement();
			int num = sta.executeUpdate(sql);
			if (num > 0) {
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} finally {
			closeAll11(null, sta, conn);
		}
		return false;
	}

	/**
	 * 查询的方法
	 * @param sql
	 * @return
	 */
	public static QueryDataResult execQuery(String sql) {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = getConn();
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			return new QueryDataResult(conn, st, rs);
		} catch (SQLException e) {
			e.printStackTrace();
			closeAll11( rs,st, conn);
			return null;
		}

	}

	/**
	 * 关闭方法
	 * 
	 * @param rs
	 * @param sta
	 * @param conn
	 */
	public static void closeAll11(ResultSet rs, Statement sta, Connection conn) {
		try {
			if (rs != null)
				rs.close();
			if (sta != null)
				sta.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void closeAll111(ResultSet rs, Statement st, Connection conn) {
		// TODO Auto-generated method stub
		
	}

	public static void closeAll1(ResultSet rs, Statement st, Connection conn) {
		// TODO Auto-generated method stub
		
	}

	public static void closeAll(ResultSet rs, Statement st, Connection conn) {
		// TODO Auto-generated method stub
		
	}

}
